import { HttpContext } from '@angular/common/http';
import { Component, inject, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import { _HttpClient } from '@delon/theme';
import { base64Str } from '@shared';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_REDIRECT_URI } from 'src/app/shared/constant/common-constant';

@Component({
  selector: 'app-oauth2',
  template: ``,
  providers: [],
  standalone: true
})
export class OauthRedirectComponent implements OnInit {
  // 获取地址栏授权码
  code: string | undefined;
  urlState: string | undefined;

  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);

  constructor() {
    this.route.queryParams.subscribe(res => {
      this.code = res['code'] || '';
      this.urlState = res['state'] || '';
    });
  }
  ngOnInit(): void {
    if (this.code) {
      const data = new FormData();
      data.append('grant_type', 'authorization_code');
      data.append('redirect_uri', OAUTH_REDIRECT_URI);
      data.append('code', this.code);
      data.append('urlState', this.urlState || '');
      this.http
        .post(`${Api.BaseOAuthApi}/token`, data, null, {
          headers: {
            Authorization: `Basic ${base64Str(`${OAUTH_CLIENT_ID}:${OAUTH_CLIENT_SECRET}`)}`
          },
          context: new HttpContext().set(ALLOW_ANONYMOUS, true)
        })
        .subscribe({
          next: (res: NzSafeAny) => {
            localStorage.setItem('accessToken', JSON.stringify(res));
            this.router.navigateByUrl('/');
          },
          error: err => {
            this.msg.warning(`请求token失败：${err.message || '未知'}`);
          }
        });
    }
  }
}
